using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using B.S.BasicData.ApiRead;
using B.S.BasicData.EroorCode;
using B.S.BasicData.Infrature;

public class BreedingInfoBatchQuery : IRequest<ApiResult<List<BreedingInfoBatchDto>>>
{
    public string BatchNo { get; set; }
}

public class BreedingInfoBatchQueryHandler : IRequestHandler<BreedingInfoBatchQuery, ApiResult<List<BreedingInfoBatchDto>>>
{
    private readonly AppDbContext _dbContext;
    public BreedingInfoBatchQueryHandler(AppDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task<ApiResult<List<BreedingInfoBatchDto>>> Handle(BreedingInfoBatchQuery request, CancellationToken cancellationToken)
    {
        var query = from b in _dbContext.BreedingInfos
                    where b.BatchNo == request.BatchNo
                    join e in _dbContext.BreedingEnterpriseInfos on b.BatchNo equals e.BatchNo into be
                    from e in be.DefaultIfEmpty()
                    join i in _dbContext.BreedingImmunityInfos on b.BatchNo equals i.BatchNo into bi
                    from i in bi.DefaultIfEmpty()
                    select new BreedingInfoBatchDto
                    {
                        BreedingInfoId = b.Id,
                        Breed = b.Breed,
                        Source = b.Source,
                        FeedingDays = b.FeedingDays,
                        FeedingBrand = b.FeedingBrand,
                        FeedingManager = b.FeedingManager,
                        OutboundDate = b.OutboundDate,
                        BatchNo = b.BatchNo,
                        EnterpriseId = e != null ? (int?)e.Id : null,
                        FarmName = e != null ? e.FarmName : null,
                        Manager = e != null ? e.Manager : null,
                        StockCount = e != null ? (int?)e.StockCount : null,
                        ImmunityId = i != null ? (int?)i.Id : null,
                        ImmunityFeedingDays = i != null ? (int?)i.FeedingDays : null,
                        ImmunityType = i != null ? i.ImmunityType : null,
                        ImmunityMethod = i != null ? i.ImmunityMethod : null,
                        ImmunityIsDeleted = i != null ? (bool?)i.IsDeleted : null
                    };
        var list = query.ToList();
        return ApiResult<List<BreedingInfoBatchDto>>.Success(list);
    }
} 